﻿using UnityEngine;
using System.Collections;

public class RobotPositionValidation : MonoBehaviour {

    public Vector3 validPosition = Vector3.zero;

    private bool collisionTriggered = false;

    private long frame = 0;

    private int wallTriggerCount = 0;

    private TeleportShotManager shotManager;

    private bool invalidArea = false;

	// Use this for initialization
	void Start () {
        shotManager = transform.parent.GetComponent<TeleportShotManager>();
	}
	
	// Update is called once per frame
	void Update () {
        frame++;

        // TODO: Force two valid positions before keeping the prior... maybe.
        // Or just look for a different validation scheme, because this one seems unreliable.

        if (!collisionTriggered)
        {
            // print("Valid position found at " + this.transform.position.ToString("F3"));
            validPosition = this.transform.position;
            if (invalidArea)
            {
                shotManager.OnInvalidAreaExit();
            }
            invalidArea = false;
        }
        else
        {
            //print("Discarding " + this.transform.position.ToString("F3"));
            if (!invalidArea)
            {
                shotManager.OnInvalidAreaEnter();
            }
            invalidArea = true;
        }
        
    }

    void LateUpdate()
    {
        //print("resetting collision trigger frame " + frame);
        collisionTriggered = (wallTriggerCount > 0);
    }

    void OnTriggerEnter(Collider collider)
    {
        if (collider.tag.EndsWith("Wall"))
        {
            wallTriggerCount++;
        }
    }

    void OnTriggerExit(Collider collider)
    {
        if (collider.tag.EndsWith("Wall"))
        {
            wallTriggerCount--;
        }
    }


    internal void Collided()
    {
        collisionTriggered = true;
    }
}
